// pages/tabs/tabs.js
Page({
  data: {
    showModal: false,//刪除
    deleteName: '香港科學館',  // 要刪除的地名
    popupVisible: false, //編輯彈框
    locationVisible:false,//我的收藏地點彈框
    selectVisible:false,//地點選擇彈框
    flightVisible:false,//航班彈框
    flightActiveTab:0,//航班彈框tab
    trainVisible:false,//列車彈框
    trainActiveTab:0,//列車彈框tab
    portVisible:false,//口岸彈框
    hotelVisible:false,//酒店彈框
    hotelActiveTab:0,//列車彈框tab
    showTimePopup: false, //日期彈框
    timePopup:false,//出發到達時間彈框
    dayPopup:false,//住宿天數彈框
    goDayPopup:false,//出发天數彈框
    timeActiveTab:'date',//出發到達攤開tab
    weekOptions: [], // ["6.29 星期二", "6.30 星期三", ...]
    hourOptions: [], // ["00", "01", "02", ...]
    minuteOptions: [], // ["00", "01", "02", ...]
    pickerValue: [0, 0, 0], // 默認選中第0項
    dayModal:false,//添加地點至彈框
    portModal:false,//添加口岸至彈框
    flightActiveTab: 0, // 當前選中的tab
    daysList:[      
      { selected: false },
      { selected: false },
      { selected: false },
      { selected: false },
      { selected: false }],
    // 航班信息
    // flightData:{
    // departure: '深圳寶安機場',      // 出發地
    // departureTime: '',  // 出發時間
    // destination: '深圳寶安機場',    // 目的地
    // arrivalTime: '',    // 到達時間
    // departureDate: '',  // 出發日期（航班信息tab）
    // flightNumber: 'G54435' ,   // 航班號
    // },
    flightSegments: [
      { departure: '深圳寶安機場', departureTime: '', destination: '深圳寶安機場', arrivalTime: '' }
    ],
    // 航班信息数组（tab=1）
    flightInfos: [
      { departureDate: '', flightNumber: 'G54435', airline: '吉祥航空', departure: '深圳寶安機場', departureTime: '7:00', 
      destination: '深圳寶安機場', arrivalTime: '10:05', duration: '3小時5分鐘' }
    ],
    // 列車信息
    // trainData:{
    //   departure: '深圳北站',      // 出發地
    //   departureTime: '',  // 出發時間
    //   destination: '深圳北站',    // 目的地
    //   arrivalTime: '',    // 到達時間
    //   departureDate: '',  // 出發日期（航班信息tab）
    //   flightNumber: 'Z298' ,   // 航班號
    // },
     // 基本信息（行程段）
     trainSegments: [
      { departure: '深圳北站', departureTime: '', destination: '深圳北站', arrivalTime: '' }
    ],
    // 列車信息
    trainInfos: [
      { departureDate: '', trainNumber: 'Z298', departure: '深圳北站', departureTime: '7:00', destination: '深圳北站', 
      arrivalTime: '10:05', duration: '3小時5分鐘' }
    ],
    // 入住信息
    hotelList: [
      { departure: "香港瑰麗酒店", departureTime: "" } // 初始一个
    ],
    // 口岸信息
    portData:{
      departure: '深圳北站',      // 出發地
      departureTime: '',  // 出發時間
      destination: '',    // 目的地
      arrivalTime: '',    // 到達時間
    },
    calendarConfig: {
      chooseAreaMode: true // 開啟範圍選擇模式
    },
    activeTab: 'date', // 默認打開天數 tab
    dayOptions: Array.from({ length: 30 }, (_, i) => i + 1),
    daysIndex:0,
    selectedDayIndex: 0,
    selectedDay: '',
    tabs: ['總覽', 'DAY'],
    activeIndex: 1,
    scrollLeft: 0,
    items: [
      { label: '地點', icon: '/pages/assets/image/didian.svg' },
      { label: '列車', icon: '/pages/assets/image/lieche.svg' },
      { label: '航班', icon: '/pages/assets/image/hangban.svg' },
      { label: '口岸', icon: '/pages/assets/image/kouan.svg' },
      { label: '酒店', icon: '/pages/assets/image/jiudian.svg' },
    ],
    // 收藏
    collectTabs:['全部', '美食', '打卡'],
    // 地點選擇
    places: [
      {
        id: 1,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: false,
      },
      {
        id: 2,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: false,
      },
      {
        id: 3,
        image: '/pages/assets/image/motianlun.jpg',
        name: '維多利亞港',
        desc: '「香港璀璨夜景的最佳觀景點...」',
        selected: true,
      },
    ],
    addDays: ['DAY 1', 'DAY 2', 'DAY 3', 'DAY 4', 'DAY 5'],
    addPort: ['福田口岸', '羅湖口岸', '皇崗口岸', '深圳灣口岸'],
    days: [
      {
        id: 1,
        title: "DAY 1",
        items: ["航班 G54435", "海港城", "尖沙咀", "太平山頂", "星光大道"]
      },
      {
        id: 2,
        title: "DAY 2",
        items: ["香港科學館", "海港城", "尖沙咀", "太平山頂", "星光大道"]
      },
      {
        id: 3,
        title: "DAY 3",
        items: ["科學館", "海港城"]
      }
    ],
     //交通選擇
     transportOptions: [
      { label: '公共交通', icon: '/pages/assets/image/bus.svg' },
      { label: '架車', icon: '/pages/assets/image/car.svg' },
      { label: '走路', icon: '/pages/assets/image/go.svg' }
    ],
     //時間選擇
     hours: Array.from({ length: 24 }, (_, i) => (i < 10 ? '0' + i : '' + i)),
     minutes: Array.from({ length: 60 }, (_, i) => (i < 10 ? '0' + i : '' + i)),
     startTime: ['08', '00'],
     endTime: ['20', '00'],
  },
   // 入住天數切換選中狀態
   toggleDay(e) {
    const index = e.currentTarget.dataset.index
    const days = this.data.daysList
    days[index].selected = !days[index].selected
    this.setData({ daysList:days })
  },
  goDay(e) { 
    const index = e.currentTarget.dataset.index;
    const days = this.data.daysList.map((item, i) => {
      return {
        ...item,
        selected: i === index // 只有点击的那个是 true
      }
    });
    this.setData({ daysList: days });
  },
  // 入住天數確認按鈕事件
  selectDayClick() {
    const selectedDays = this.data.daysList
      .map((d, i) => d.selected ? `DAY ${i + 1}` : null)
      .filter(Boolean)
    console.log('選中的天數:', selectedDays)
    this.setData({
      dayPopup:false,
      goDayPopup:false
    })
  },
  portClick(){
    this.setData({
      portModal:false
    })
  },
  //選擇地點
  toggleSelect(e) {
    const id = e.currentTarget.dataset.id;
    const places = this.data.places.map(p => {
      if (p.id === id) p.selected = !p.selected;
      return p;
    });
    this.setData({ 
      places,
      dayModal:true
     });
  },
  confirmSelect(){

  },
  //添加列表選擇
  scrollClick(e){
    const index = e.currentTarget.dataset.index
    if(index==0){
      this.setData({
        selectVisible:true
      })
    }else if (index == 1){
      this.setData({
        trainVisible:true
      })
    }else if (index == 2){
      this.setData({
        flightVisible:true
      })
    }else if (index == 3){
      this.setData({
        portVisible:true
      })
    }else if (index == 4){
      this.setData({
        hotelVisible:true
      })
    }
    
  },
  goToFavorites(){
    this.setData({
      selectVisible:false,
        locationVisible:true,
    })
  },
  //日期彈框tab
  switchTabTime(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ activeTab: tab });
  },
  // 航班tab
  flightSwitchTab(e) {
    const index = Number(e.currentTarget.dataset.index);
    this.setData({ flightActiveTab: index });
  },
    // 航班輸入事件
    // tab=0 输入
  onSegmentInput(e) {
    const { index, field } = e.currentTarget.dataset;
    let list = this.data.flightSegments;
    list[index][field] = e.detail.value;
    this.setData({ flightSegments: list });
    console.log(list);
  },

  // tab=1 输入
  onFlightInfoInput(e) {
    const { index, field } = e.currentTarget.dataset;
    let list = this.data.flightInfos;
    list[index][field] = e.detail.value;
    this.setData({ flightInfos: list });
  },
    // 添加一个住宿项
  addItem() {
    let list = this.data.hotelList;
    list.push({ departure: "", departureTime: "",title:`住宿` });
    this.setData({
      hotelList: list
    });
  },
    // 基本信息输入
    onTrainSegmentInput(e) {
      const { index, field } = e.currentTarget.dataset;
      let list = this.data.trainSegments;
      list[index][field] = e.detail.value;
      this.setData({ trainSegments: list });
    },
  
    // 列車信息输入
    onTrainInfoInput(e) {
      const { index, field } = e.currentTarget.dataset;
      let list = this.data.trainInfos;
      list[index][field] = e.detail.value;
      this.setData({ trainInfos: list });
    console.log(list);
  },
  
    // 添加行程段
    addTrainSegment() {
      let list = this.data.trainSegments;
      list.push({ departure: '', departureTime: '', destination: '', arrivalTime: '',title:'列车' });
      this.setData({ trainSegments: list });
    },
  
    // 添加列車信息
    addTrainInfo() {
      let list = this.data.trainInfos;
      list.push({ departureDate: '', trainNumber: '', departure: '', departureTime: '', destination: '', arrivalTime: '', duration: '',
    title:'列车信息' });
      this.setData({ trainInfos: list });
    },
  // 添加航程段
  addSegment() {
    let list = this.data.flightSegments;
    list.push({ departure: '', departureTime: '', destination: '', arrivalTime: '',title:`航班` });
    this.setData({ flightSegments: list });
  },

  // 添加航班信息
  addFlightInfo() {
    let list = this.data.flightInfos;
    list.push({ departureDate: '', flightNumber: '', airline: '', departure: '', departureTime: '', destination: '', arrivalTime: '', duration: '',title:`航班信息` });
    this.setData({ flightInfos: list });
  },
  // 输入住宿点
  onHotelInput(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    let list = this.data.hotelList;
    list[index].departure = value;
    this.setData({ hotelList: list });
  },
    // 時間選擇事件（只是示例）
    selectDepartureTime() {
      this.setData({
        goDayPopup:true
      })
    },
    selectArrivalTime() {
      this.setData({
        goDayPopup:true
      })
    },
    portShow(){
      this.setData({
        portModal:true
      })
    },
    // 住宿天數彈框
    selectHotelDay(){
      this.setData({
        dayPopup:true
      })
    },
  openPopup() {
    this.setData({ showTimePopup: true });
  },

  closePopup() {
    this.setData({ showTimePopup: false });
  },
  // 日期改變
  onDayPickerChange(e) {
    console.log(e.detail.value[0]);
    this.setData({
      selectedDayIndex: e.detail.value[0]
    });
  },
  onDayPickerChange2(e) {
    console.log(e.detail.value[0]);
    this.setData({
      daysIndex: e.detail.value[0]
    });
  },
  // 交通點擊
  onSelectTransport(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      selectedTransportIndex: index
    });
  },
  // 時間改變
  onStartTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({ startTime: [hour, minute] });
    console.log('開始時間：', hour + ':' + minute);
  },

  onEndTimeChange(e) {
    const hour = this.data.hours[e.detail.value[0]];
    const minute = this.data.minutes[e.detail.value[1]];
    this.setData({ endTime: [hour, minute] });
    console.log('結束時間：', hour + ':' + minute);
  },
  // 點擊切換Tab
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      activeIndex: index,
      scrollLeft: (index - 1) * 60 // 滾動到合適位置
    });
  },
  timeSwitchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({ timeActiveTab: tab });
  },

  // 滑動切換Tab
  // swiperChange(e) {
  //   const index = e.detail.current;
  //   this.setData({
  //     activeIndex: index,
  //     scrollLeft: (index - 1) * 60
  //   });
  // },
  onLoad() {
    this.initPickerData();
  },

  // 初始化選擇器數據
  initPickerData() {
    // 生成 7 天日期 + 星期幾
    const days = [];
    const weekDays = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
    const now = new Date();
    for (let i = 0; i < 7; i++) {
      const date = new Date();
      date.setDate(now.getDate() + i);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const week = weekDays[date.getDay()];
      days.push(`${month}.${day} ${week}`);
    }

    // 小時
    const hours = [];
    for (let i = 0; i < 24; i++) {
      hours.push(i < 10 ? '0' + i : '' + i);
    }

    // 分鐘
    const minutes = [];
    for (let i = 0; i < 60; i++) {
      minutes.push(i < 10 ? '0' + i : '' + i);
    }
    console.log(days);
    this.setData({
      weekOptions: days,
      hourOptions: hours,
      minuteOptions: minutes
    });
  },

  // 選擇器滾動事件
  selectStart(e) {
    const val = e.detail.value; // [dayIndex, hourIndex, minuteIndex]
    console.log('當前選擇：', 
      this.data.weekOptions[val[0]], 
      this.data.hourOptions[val[1]], 
      this.data.minuteOptions[val[2]]
    );
    this.setData({ pickerValue: val });
  },
  selectEnd(e) {
    const val = e.detail.value; // [dayIndex, hourIndex, minuteIndex]
    console.log('當前選擇：', 
      this.data.weekOptions[val[0]], 
      this.data.hourOptions[val[1]], 
      this.data.minuteOptions[val[2]]
    );
    this.setData({ 
      pickerValue: val, 
     });
  },
  selectTimeClick(){ 
    this.setData({
      timePopup:false,
      dayPopup:false
    })
  },
  // 打開彈框
  showPopup() {
    this.setData({ popupVisible: true });
  },

  // 關閉彈框
  hidePopup() {
    this.setData({ 
      popupVisible: false,
      locationVisible:false,
      selectVisible:false,
      flightVisible:false,
      trainVisible:false,
      hotelVisible:false,
      portVisible:false,
     });
  },
    // 顯示彈框
    showDeleteDialog(e) {
      const name = e.currentTarget.dataset.name;
      this.setData({
        showModal: true,
        deleteName: name
      });
    },
  
    // 點擊遮罩或取消
    closeModal() {
      this.setData({
        showModal: false,
        dayModal: false,
        
      });
    },
  
    // 阻止遮罩點擊冒泡
    stopTap() {},
  
    // 確認刪除
    confirmDelete() {
      const name = this.data.deleteName;
      this.setData({
        showModal: false
      });
    },
  // --- 滑動刪除 ---
  handleTouchStart(e) {
    const index = e.currentTarget.dataset.index;
    this.startX = e.touches[0].clientX;
    this.resetSwipe();
  },

  handleTouchMove(e) {
    const moveX = e.touches[0].clientX;
    const disX = this.startX - moveX;
    const index = e.currentTarget.dataset.index;

    if (disX > 30) {
      this.setSwipe(index, true);
    } else if (disX < -30) {
      this.setSwipe(index, false);
    }
  },

  handleTouchEnd(e) {},

  handleTouchCancel() {
    this.resetSwipe();
  },

  setSwipe(index, status) {
    const days = this.data.days.map((item, i) => {
      return { ...item, isTouchMove: i === index ? status : false };
    });
    this.setData({ days });
  },

  resetSwipe() {
    const days = this.data.days.map(item => ({ ...item, isTouchMove: false }));
    this.setData({ days });
  },

  deleteItem(e) {
    const index = e.currentTarget.dataset.index;
    const days = this.data.days.filter((_, i) => i !== index);
    this.setData({ days });
  },

  // --- 拖拽排序 ---
  dragStart(e) {
    this.dragIndex = e.currentTarget.dataset.index;
    this.startY = e.touches[0].clientY;
  },

  dragMove(e) {
    const moveY = e.touches[0].clientY;
    const deltaY = moveY - this.startY;

    if (Math.abs(deltaY) > 60) {
      const { days } = this.data;
      const dragIndex = this.dragIndex;
      const targetIndex = deltaY > 0 ? dragIndex + 1 : dragIndex - 1;

      if (targetIndex < 0 || targetIndex >= days.length) return;

      const temp = days[dragIndex];
      days[dragIndex] = days[targetIndex];
      days[targetIndex] = temp;

      this.dragIndex = targetIndex;
      this.setData({ days });
      this.startY = moveY;
    }
  },

  dragEnd() {
    // 更新完成，重新編號
    const updated = this.data.days.map((item, index) => ({
      ...item,
      title: `DAY ${index + 1}`
    }));
    this.setData({ days: updated });
  },
  goRouteClick(){
    wx.navigateTo({
      url: '/pages/Itinerary/routeDetailsEdit/routeDetailsEdit',
    })
  }
})